package com.ww.microrpc;

import com.ww.microrpc.netty.NettyServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.ApplicationListener;

public class MicroRpcServiceRegisterListener implements ApplicationListener<WebServerInitializedEvent> {

    /**
     * 这里可能是 EurekaServiceRegistry 或者 NacosServiceRegistry
     */
    @Autowired
    private ServiceRegistry<Registration> serviceRegistry;
    @Autowired
    private InetUtils inetUtils;
    @Autowired
    private RegisterDiscoveryProperties registerDiscoveryProperties;
    @Autowired
    private NettyServerConfig nettyServerConfig;

    public ServiceRegistry<Registration> getServiceRegistry() {
        return serviceRegistry;
    }

    public void setServiceRegistry(ServiceRegistry<Registration> serviceRegistry) {
        this.serviceRegistry = serviceRegistry;
    }

    public InetUtils getInetUtils() {
        return inetUtils;
    }

    public void setInetUtils(InetUtils inetUtils) {
        this.inetUtils = inetUtils;
    }

    public RegisterDiscoveryProperties getRegisterDiscoveryProperties() {
        return registerDiscoveryProperties;
    }

    public void setRegisterDiscoveryProperties(RegisterDiscoveryProperties registerDiscoveryProperties) {
        this.registerDiscoveryProperties = registerDiscoveryProperties;
    }

    public NettyServerConfig getNettyServerConfig() {
        return nettyServerConfig;
    }

    public void setNettyServerConfig(NettyServerConfig nettyServerConfig) {
        this.nettyServerConfig = nettyServerConfig;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        if (registerDiscoveryProperties.getEnabled() && nettyServerConfig.getEnabled()) {
            MicroRpcServiceRegistration registration = new MicroRpcServiceRegistration();
            registration.setServiceId(registerDiscoveryProperties.getServiceName() + "-rpc");
            registration.setPort(nettyServerConfig.getPort());
            registration.setHost(inetUtils.findFirstNonLoopbackHostInfo().getIpAddress());
            serviceRegistry.register(registration);
        }
    }
}
